//
//  UIControl+Add.swift
//  HHSwift
//
//  Created by qk-huahong on 2019/8/5.
//  Copyright © 2019 huahong. All rights reserved.
//

import Foundation

protocol SwizzleProtocol: class {
    static func awake()
    static func swizzlingForClass(_ forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector)
}

extension SwizzleProtocol {
    
    static func swizzlingForClass(_ forClass: AnyClass, originalSelector: Selector, swizzledSelector: Selector) {
        let originalMethod = class_getInstanceMethod(forClass, originalSelector)
        let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector)
        guard (originalMethod != nil && swizzledMethod != nil) else {
            return
        }
        if class_addMethod(forClass, originalSelector, method_getImplementation(swizzledMethod!), method_getTypeEncoding(swizzledMethod!)) {
            class_replaceMethod(forClass, swizzledSelector, method_getImplementation(originalMethod!), method_getTypeEncoding(originalMethod!))
        } else {
            method_exchangeImplementations(originalMethod!, swizzledMethod!)
        }
    }
}

extension UIApplication {
   
    override open var next: UIResponder? {
        
        UIApplication.runOnce
        return super.next
    }
    
    private static let runOnce: Void = {

        let typeCount = Int(objc_getClassList(nil, 0))
        let types = UnsafeMutablePointer<AnyClass>.allocate(capacity: typeCount)
        let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass>(types)
        objc_getClassList(autoreleasingTypes, Int32(typeCount))
        for index in 0 ..< typeCount {
            (types[index] as? SwizzleProtocol.Type)?.awake()
        }
        types.deallocate()
    }()
}


extension UIControl:SwizzleProtocol{
    static func awake() {
        let originalSelector = #selector(sendAction(_:to:for:))
        let swizzledSelector = #selector(swizzled_sendAction(_:to:for:))
        
        swizzlingForClass(UIButton.self, originalSelector: originalSelector, swizzledSelector: swizzledSelector)
    }
    
    
     @objc public func swizzled_sendAction(_ action: Selector, to target: Any?, for event: UIEvent?){

        print("swizzled_sendAction")
        swizzled_sendAction(action, to: target, for: event)
    }
    
   
}



